package com.hot12345.springmvc.admin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.hot12345.common.spring.SpringAbstractController;
import com.hot12345.common.util.IPUtil;
import com.hot12345.dao.ClickDaoImpl;
import com.hot12345.dao.InfoDaoImpl;
import com.hot12345.dao.ItemDaoImpl;
import com.hot12345.dao.SiteDaoImpl;
import com.hot12345.entity.Info;
import com.hot12345.entity.Item;
import com.hot12345.entity.Site;
import com.hot12345.entity.User;
import com.hot12345.service.ClickServiceImpl;
import com.hot12345.vo.InfoVO;

@Controller
@RequestMapping("/admin/info")
public class InfoController extends SpringAbstractController {
	
	private final static Log log = LogFactory.getLog(InfoController.class);

	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap,
			@RequestParam int itemID) throws Exception {
//		@RequestParam(value="itemchildid", required=false) String itemChildId,
		
		modelMap.put("pageSize", 20);
		pageBefore(request, modelMap);
		
		if(itemID>=0){
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("itemID", itemID);
			params.put("state_gte", 0);
			params.put("order", "isTop desc,topTime desc,id desc");
			InfoDaoImpl infoDao = InfoDaoImpl.getInstance();
			List<Info> infoList = infoDao.findByParamsPage(params, getStartNo(modelMap), getPageSize(modelMap));
			long totalNum =infoDao.findCount(params);
			pageAfter(request, totalNum, modelMap);
			modelMap.put("infoList", infoList);
		}
		
		//栏目
		ItemDaoImpl itemDao = ItemDaoImpl.getInstance();
		Map<String,Object> itemParams = new HashMap<String, Object>();
		itemParams.put("state", 1);
		List<Item> itemList = itemDao.findByParams(itemParams);
		modelMap.put("itemList", itemList);
		
		Item item = itemDao.findByPrimaryKey(itemID);
		modelMap.put("item", item);
		modelMap.put("itemID", itemID);
		
		return new ModelAndView("admin/info/infoList");
	}
	
	@RequestMapping(value="/add",method = RequestMethod.GET)
	public ModelAndView add(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap,
			@RequestParam int itemID) throws Exception {
		
		//栏目
		ItemDaoImpl itemDao = ItemDaoImpl.getInstance();
		Map<String,Object> itemParams = new HashMap<String, Object>();
		itemParams.put("state", 1);
		List<Item> itemList = itemDao.findByParams(itemParams);
		modelMap.put("itemList", itemList);
		
		Item item = itemDao.findByPrimaryKey(itemID);
		modelMap.put("item", item);
		
		Map<String,Object> stieParams = new HashMap<String,Object>();
		stieParams.put("state", "1");
		SiteDaoImpl siteDao = SiteDaoImpl.getInstance();
		List<Site> siteList = siteDao.findByParams(stieParams);
		modelMap.put("siteList", siteList);
		
		return new ModelAndView("admin/info/infoAdd");
	}
	
	@RequestMapping(value="/insert",method = RequestMethod.POST)
	public ModelAndView insert(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap,
			@RequestParam String title,
			@RequestParam String url,
			@RequestParam(value = "imgUrl", required = false) String imgUrl,
			@RequestParam(value = "review", required = false) String  review,
			@RequestParam int client,
			@RequestParam int siteID,
			@RequestParam int itemID) throws Exception{
		
		SiteDaoImpl siteDao = SiteDaoImpl.getInstance();
		Site site = siteDao.findByPrimaryKey(siteID);
		
		User user = (User)modelMap.get("loginUser");
		Info info = new Info();
		info.setClient(client);
		if(user!=null){
			info.setCreateUserID(user.getId());
		}
		
		info.setCreateDate(new Date());
		info.setItemID(itemID);
		info.setSiteID(siteID);
		if(site!=null){
			info.setSiteName(site.getName());
		}
		info.setParentID(0L);//默认为0,即没有进行关联。
		info.setState(0);//默认为屏蔽
		info.setTitle(title);
		info.setUrl(url);
		info.setImgUrl(imgUrl);
		info.setReview(review);
		
		InfoDaoImpl infoDao = InfoDaoImpl.getInstance();
		infoDao.insertL(info);
		
		response.sendRedirect("/admin/info/index?itemID="+itemID);
		return null;
	}
	
	@RequestMapping(value="/edit", method = RequestMethod.GET)
	public ModelAndView edit(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap,
			int id) throws Exception {
		
		InfoDaoImpl infoDao = InfoDaoImpl.getInstance();
		Info info = infoDao.findByPrimaryKey(id);
		modelMap.put("info", info);
		
		if(info==null || info.getItemID()==null){
			log.error("info==null || info.getItemID==null, id="+id);
		} else {
			ItemDaoImpl itemDao = ItemDaoImpl.getInstance();
			Item item = itemDao.findByPrimaryKey(info.getItemID());
			modelMap.put("item", item);
		}
		
		SiteDaoImpl siteDao = SiteDaoImpl.getInstance();
		Site site = siteDao.findByPrimaryKey(info.getSiteID());
		modelMap.put("site", site);
		
		Map<String,Object> stieParams = new HashMap<String,Object>();
		stieParams.put("state", "1");
		List<Site> siteList = siteDao.findByParams(stieParams);
		modelMap.put("siteList", siteList);
		
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("state", 1);
		ItemDaoImpl itemDao = ItemDaoImpl.getInstance();
		List<Item> itemList = itemDao.findByParams(params);
		modelMap.put("itemList", itemList);
		
		return new ModelAndView("admin/info/infoEdit");
	}
	
	@RequestMapping(value="/update", method = RequestMethod.POST)
	public void update(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap,
			long id,
			String title,
			int client,
			int itemID,
			String url,
			@RequestParam(value = "imgUrl", required = false) String imgUrl,
			@RequestParam(value = "review", required = false) String  review,
			int siteID) throws Exception {
		
		SiteDaoImpl siteDao = SiteDaoImpl.getInstance();
		Site site = siteDao.findByPrimaryKey(siteID);
		
		InfoDaoImpl infoDao = InfoDaoImpl.getInstance();
		Info info = infoDao.findByPrimaryKey(id);
		
		int oldItemID = 0;
		try{
			oldItemID = info.getItemID();
		}catch(Exception e){
			log.error("转换itemID异常", e);
		}
		
		info.setId(id);
		info.setClient(client);
		info.setItemID(itemID);
		info.setSiteID(siteID);
		if(site!=null){
			info.setSiteName(site.getName());
		}
		info.setTitle(title);
		info.setUrl(url);
		info.setImgUrl(imgUrl);
		info.setReview(review);
		infoDao.update(info);
		
		
		
		//更改了栏目，需要同时更新click表
		if(oldItemID!=itemID){
			if(info.getParentID()!=0 && info.getParentID()!=id){
				log.error("更新栏目异常，当前信息不允许更改栏目,id="+id + ",itemID="+itemID);
				throw new Exception("更新栏目异常，当前信息不允许更改栏目");
			}		
			
			//更新主信息栏目 
			ClickDaoImpl clickDao = ClickDaoImpl.getInstance();
			
//			Click click = clickDao.findByPrimaryKey(id);
//			click.setItemID(itemID);
//			click.setInfoID(id);
			clickDao.updateItem(id,null,itemID);//将infoID相同的都更新
			
			//更新每一条子记录,将parentID相同的更新
			clickDao.updateItem(null, id, itemID);
		}
		
		response.sendRedirect("/admin/info/index?itemID="+itemID);
	}
	
	/**
	 * 冻结
	 *	
	 * @param request
	 * @param response
	 * @param modelMap
	 * @param id
	 * @throws Exception
	 * @author wuzongbao
	 * @date 2013-3-3 下午11:48:23
	 * @version V1.0
	 */

	@RequestMapping(value="/freeze", method = RequestMethod.GET)
	public void freeze(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap,
			long id) throws Exception {
		
		InfoDaoImpl infoDao = InfoDaoImpl.getInstance();
		Info info = infoDao.findByPrimaryKey(id);
		info.setState(0);
		infoDao.update(info);
		
		//将点击记录也冻结
		ClickDaoImpl clickDao = ClickDaoImpl.getInstance();
		clickDao.freeze(id);
		
		response.sendRedirect("/admin/info/index?itemID="+info.getItemID());
	}
	
	/**
	 * 恢复正常状态
	 *	
	 * @param request
	 * @param response
	 * @param modelMap
	 * @param id
	 * @throws Exception
	 * @author wuzongbao
	 * @date 2013-3-3 下午11:48:43
	 * @version V1.0
	 */
	@RequestMapping(value="/restore", method = RequestMethod.GET)
	public void restore(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap,
			long id) throws Exception {
		
		InfoDaoImpl infoDao = InfoDaoImpl.getInstance();
		Info info = infoDao.findByPrimaryKey(id);
		info.setState(1);
		infoDao.update(info);
		
		//将点击记录恢复正常
		ClickDaoImpl clickDao = ClickDaoImpl.getInstance();
		clickDao.restore(id);
		
		//模拟一次点击，增加一条访问记录
		String ip = IPUtil.getUserIP(request);
		ClickServiceImpl.addClickNum(id, ip);
		
		response.sendRedirect("/admin/info/index?itemID="+info.getItemID());
	}
	
	@RequestMapping(value="/delete", method = RequestMethod.GET)
	public void delete(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap,
			long id,
			int itemID) throws Exception {
		InfoDaoImpl infoDao = InfoDaoImpl.getInstance();
		infoDao.deleteByPrimaryKey(id);
		
		response.sendRedirect("/admin/info/index?itemID="+itemID);
	}
	
	@RequestMapping(value="/dataJoin", method = RequestMethod.GET)
	public ModelAndView dataJoin(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap,
			String ids)throws Exception {
		log.debug("ids="+ids);
		String[] idArr = ids.split(",");
		List<Integer> idList = new ArrayList<Integer>();
		if(idArr!=null && idArr.length>0){
			try{
				for(int i=0; i<idArr.length; i++){
					if(idArr[i]!=null && !"".equals(idArr[i])){
						idList.add(Integer.valueOf(idArr[i]));
					}
				}
			}catch(Exception e){
				log.error("转换信息ID错误", e);
			}
		}
		
		if(idList.size()>0){
			Map<String,Object> params = new HashMap<String, Object>();
			params.put("idList", idList);
			InfoDaoImpl infoDao = InfoDaoImpl.getInstance();
			List<InfoVO> infoList = infoDao.findByIds(params);
			modelMap.put("infoList", infoList);
		}
		return new ModelAndView("admin/info/chose");
	}
	
	@RequestMapping("/relation")
	public void relation(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap,
			long primaryID)throws Exception {

		String[] ids = (String[])request.getParameterValues("id");
		if(ids==null || ids.length==0){
			printMsg(response, "错误，没有选择数据。");
			return;
		}
		
		int[] intIds = new int[ids.length];
		for(int i=0; i<ids.length; i++){
			try{
				intIds[i] = Integer.valueOf(ids[i]);
			}catch(Exception e){
				log.error("转换数据ID异常", e);
				printMsg(response, "错误，id转换异常。");
				return ;
			}
		}
		
		InfoDaoImpl infoDao = InfoDaoImpl.getInstance();
//		Map<String,Object> params = new HashMap<String,Object>();
//		params.put("idList", intIds);
//		List list = infoDao.findByIds(params);
	
		int succ = 0;
		int total = intIds.length;
		for(int i=0; i<total; i++){
			Info info = infoDao.findByPrimaryKey(intIds[i]);
			if(info==null || info.getId()==null || info.getId().intValue()==primaryID){
				continue;
			}
			info.setParentID(primaryID);
			int ret = infoDao.update(info);
			if(ret==1){
				succ +=1;
			}
		}
		
		printMsg(response, "设置成功,总数："+total + ",成功："+succ);
	}
	
	/**
	 * 置顶
	 *	
	 * @param request
	 * @param response
	 * @param modelMap
	 * @param primaryID
	 * @throws Exception
	 * @author wuzongbao
	 * @date 2013-5-15 下午09:41:17
	 * @version V1.0
	 */
	@RequestMapping("/top")
	public void top(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap,
			long id,int itemID)throws Exception {
		InfoDaoImpl infoDao = InfoDaoImpl.getInstance();
		try {
			int ret = infoDao.setIsTop(id);
		} catch (Exception e) {
			log.error("置顶错误", e);
		}
		
		response.sendRedirect("/admin/info/index?itemID="+itemID);
	}
	
	/**
	 * 取消置顶
	 *	
	 * @param request
	 * @param response
	 * @param modelMap
	 * @param primaryID
	 * @author wuzongbao
	 * @date 2013-5-15 下午09:41:28
	 * @version V1.0
	 * @throws IOException 
	 */
	@RequestMapping("/calcelTop")
	public void calcelTop(HttpServletRequest request,HttpServletResponse response, ModelMap modelMap,
			long id,int itemID) throws IOException{
		InfoDaoImpl infoDao = InfoDaoImpl.getInstance();
		try {
			int ret = infoDao.cancelTop(id);
		} catch (Exception e) {
			log.error("取消置顶错误", e);
		}
		
		response.sendRedirect("/admin/info/index?itemID="+itemID);
	}
}
